package com.cszy.yydqbfq.viewmodel

import AudioLoadRepository
import android.content.Context
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.cszy.yydqbfq.R
import com.cszy.yydqbfq.base.BaseViewModel
import com.cszy.yydqbfq.bean.AudioItemBean
import com.cszy.yydqbfq.bean.IndexGridBean
import com.cszy.yydqbfq.utils.SpUtils
import com.hlyj.http.base.tool.lib_hlyj_base.bean.BaseResult
import com.hlyj.http.base.tool.lib_hlyj_base.bean.music.MusicListBean
import com.hlyj.http.base.tool.lib_hlyj_base.net.ApiCallback
import com.hlyj.http.base.tool.lib_hlyj_base.utils.BaseAppConstans
import com.lzx.starrysky.SongInfo
import com.ok.common.api.GlobalApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.litepal.LitePal

class IndexViewModel:BaseViewModel() {
    private lateinit var AudioLoadRespository: AudioLoadRepository
    fun init(context: Context) {
        AudioLoadRespository = AudioLoadRepository(context.applicationContext)
    }



    /**
     * 从本地获取音频列表(有则从数据库获取)
     */
    suspend fun getAudioInfoListSync(): List<AudioItemBean> = withContext(Dispatchers.IO) {
        try {
            val localList = LitePal.findAll(AudioItemBean::class.java)
            if (localList.isNotEmpty()) {
                return@withContext localList
            }
            val remoteList = AudioLoadRespository.loadAudioFiles()
            LitePal.saveAll(remoteList)
            remoteList
        } catch (e: Exception) {
            Log.e("AudioViewModel", "Error fetching audio list", e)
            emptyList()
        }
    }

    /**
     * 从本地获取音频列表(直接从本地更新)
     */
    suspend fun getAudioInfoListSync_onlylocal(): List<AudioItemBean> = withContext(Dispatchers.IO) {
        try {

            val remoteList = AudioLoadRespository.loadAudioFiles()
            val localList = LitePal.findAll(AudioItemBean::class.java)
            if (localList.isNotEmpty()) {
                return@withContext localList
            }
            LitePal.saveAll(remoteList)
            remoteList
        } catch (e: Exception) {
            Log.e("AudioViewModel", "Error fetching audio list", e)
            emptyList()
        }
    }



    private val _queryResult = MutableLiveData<List<MusicListBean?>?>()
    val queryMusicResult: LiveData<List<MusicListBean?>?> = _queryResult

    private val _errorMessage = MutableLiveData<String>()
    val errorMessage: LiveData<String> = _errorMessage
    //获取所有音频数据
    fun queryMusic() {
        var list= LitePal.findAll(MusicListBean::class.java)
        if (list.isNotEmpty()){
            _queryResult.postValue(list)
        }else{
            GlobalApi.getMusicList("",object :
                ApiCallback<BaseResult<List<MusicListBean?>?>> {


                override fun onSuccess(result: BaseResult<List<MusicListBean?>?>) {
                    LitePal.saveAll(result.data as List<MusicListBean>)
                    _queryResult.postValue(result?.data)
                }

                override fun onFailure(errorMessage: String) {
                    _errorMessage.postValue(errorMessage)
                }

                override fun onFinish() {

                }

            })
        }

    }
   //获取category为流行的音频数据从数据库或者网络获取
    fun queryMusicByCategory(category: String) {
       // 分割分类字符串（如 "流行,说唱" -> ["流行", "说唱"]）
       val categories = category.split(",").map { it.trim() }

       // 构建 SQL 条件（匹配任意一个分类）
       val whereClause = categories.joinToString(" OR ") { "category LIKE ?" }
       val whereArgs = categories.map { "%$it%" }.toTypedArray()

       // 本地数据库查询
       val list = LitePal.where(whereClause, *whereArgs).find(MusicListBean::class.java)
       if (list.isNotEmpty()){
            _queryResult.postValue(list)
        }else{
            GlobalApi.getMusicList(category,object :
                ApiCallback<BaseResult<List<MusicListBean?>?>> {
                override fun onSuccess(result: BaseResult<List<MusicListBean?>?>) {
                    _queryResult.postValue(result?.data)

                }

                override fun onFailure(errorMessage: String) {
                    _errorMessage.postValue(errorMessage)
                }

                override fun onFinish() {

                }

            })
        }
    }


    /**
     * 获取首页gridbean数据
     */
    fun getIndexGridData():List<IndexGridBean>{
        return listOf(
            IndexGridBean("推荐",R.mipmap.ic_index_gradbg,R.mipmap.ic_sub_index_grad,"精选好歌"),
            IndexGridBean("流行", R.mipmap.ic_index_gradbg,R.mipmap.ic_sub_index_grad,"旋律简洁流畅"),
            IndexGridBean("怀旧",R.mipmap.ic_huaijiu_index, R.mipmap.ic_sub_huaijiu_index,"是回忆加了分"),
            IndexGridBean("摇滚",R.mipmap.ic_yaogun_index,R.mipmap.ic_sub_yaogun_index,"国摇天花板"),
            IndexGridBean("民谣",R.mipmap.ic_mingyao_index,R.mipmap.ic_sub_mingyao_index,"人间烟火气"),
            IndexGridBean("说唱",R.mipmap.ic_shuochang_index,R.mipmap.ic_sub_shuochang_index,"动感的鼓点",),
            IndexGridBean("国风",R.mipmap.ic_guofeng_index,R.mipmap.ic_sub_guofeng_index,"清韵诉流年"),
        )
    }


    /**
     * 初始化
     */
    //网络获取的音乐转songInfo
    fun convertToSongInfoList(musicList: List<MusicListBean>): List<SongInfo> {
        var  app_process = SpUtils.getInstance().getString(BaseAppConstans.APP_PROCESS)
        val songInfoList = musicList.mapIndexed { index, musicBean ->
            SongInfo().apply {
                songId = index.toString() // 使用下标作为ID
                songUrl = musicBean.songUrl ?: ""
                songName = if (app_process=="0"){musicBean.alias?: ""}else{musicBean.name ?: ""}
                artist = musicBean.author ?: ""
                songCover = musicBean.imageUrl ?: ""
                // 其他字段根据需要设置默认值
                duration = -1
                decode = false
            }
        }
        return songInfoList
    }
    //本地获取的音乐转songInfo
    fun convertToLocalSongInfoList(musicList: List<AudioItemBean>): List<SongInfo> {
        val songInfoList = musicList.mapIndexed { index, audioItem ->
            SongInfo().apply {
                songId = index.toString() // Using the actual ID from AudioItemBean
                songUrl = audioItem.path ?: ""
                songName = audioItem.title ?: ""
                artist = audioItem.artist ?: ""
                songCover = "" // AudioItemBean doesn't have imageUrl, so we set empty
                duration = audioItem.duration // Convert Long to Int if needed
                decode = false
            }
        }
        return songInfoList
    }

    //本地获取的音乐转成后台获取的MusicListBean
    fun convertToMusicListBeanList(audioItemList: List<AudioItemBean>): List<MusicListBean> {
        return audioItemList.mapIndexed { index, audioItem ->
            MusicListBean().apply {
                id = index// Using the actual ID from AudioItemBean
                name = audioItem.title
                author = audioItem.artist
                imageUrl = "" // AudioItemBean doesn't have imageUrl, so we set empty
                songUrl = audioItem.path
                category = "本地音乐" // You might want to set this based on your requirements

            }
        }
    }

    /**
     * taglist
     */
    fun getRandomTag(): String {
        return getTagList().random()
    }

    fun getTagList(): List<String> {
        return listOf(
            "重温经典",
            "平凡岁月",
            "流行金曲"
        )
    }
}